package thread;




class MyBlockingQueue{
   private String[] data = null;
   private int head = 0;
   private int tail = 0;
   private int size = 0;
   public MyBlockingQueue(int capacity){
       data = new String[capacity];
   }
   public  void put(String s) throws InterruptedException {
       synchronized (this){
           if(size==data.length){
                this.wait();
           }
           data[tail++] = s;
           if(tail>=data.length){
               tail = 0;
           }
           size++;
           this.notify();
       }

   }
   public String take(){
       String ret = "";
       synchronized (this){
           if(size==0){
               try {
                   this.wait();
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
           }
           ret = data[head++];
           if(head>= data.length){
               head = 0;
           }
           size--;
           this.notify();
           return ret;
       }

   }
}

public class HW8 {
    public static void main(String[] args) {
        MyBlockingQueue q = new MyBlockingQueue(1000);
        //生产者线程
        Thread t1 = new Thread(()->{
            int i = 1;
            while(true){
                try {
                    q.put(""+i);
                    System.out.println("生产元素"+i);
                    i++;
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
        });
        //消费者线程
        Thread t2 = new Thread(()->{
            while(true){
                int i = Integer.parseInt(q.take());
                System.out.println("消费元素"+i);
            }
        });
        t1.start();
        t2.start();
    }
}
